<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se tem permissao
validaPermissao(3);

// Verifica se ha locacao para ver
if (!$_GET['id'] && !$_POST['id'])
{
	forbidden();
}

// Verifica se houve envio do formulario.
if ($_POST['submit'] == 'Submit')
{
    // Checa integridade dos tickets ranges
	for ($c=0; $c < count($_POST['ticket_starts']); $c++)
	{
        if ($_POST['ticket_starts'][$c] == '' || $_POST['ticket_ends'][$c] == '')
        {
            header( "Location: location_edit.php?id={$_POST['id']}&msg=" . urlencode("Could not update location: Empty ticket range was given.") );
            die();
        }
    }

    // Efetua "limpeza" deleta ticket_ranges
    query_bd("DELETE FROM ticket_ranges WHERE location_id={$_POST['id']}");

	// Insere ticket_ranges
	for ($c=0; $c < count($_POST['ticket_starts']); $c++)
	{
		query_bd("INSERT INTO ticket_ranges VALUES " .
		"(NULL, {$_POST['id']}, {$_POST['ticket_starts'][$c]}, {$_POST['ticket_ends'][$c]} )");
	}

    // Atualiza location
	query_bd("UPDATE locations SET " .
	"workingtime= ". ($_POST['workingtime']? "'{$_POST['workingtime']}'" : "NULL") .
	", valet_payrate= {$_POST['valet_payrate']}" .
	", manager_payrate= {$_POST['manager_payrate']}" .
	", insurance_tax= {$_POST['insurance_tax']}" .
	", tip_percent= " . ($_POST['tip_percent'] / 100.0) .
	", obs= ". ($_POST['obs']? "'" . mysql_real_escape_string($_POST['obs']) . "'" : "NULL") .
	" WHERE id={$_POST['id']} LIMIT 1");

	// descobre o numero do contato
	$contacts = query_fetch("SELECT locationcontact, managercontact FROM locations WHERE id={$_POST['id']} LIMIT 1");

	// Atualiza contatos
	query_bd("UPDATE contacts SET " .
	"name=" . ($_POST['location_name']? "\"{$_POST['location_name']}\"" : "NULL") .
	", number=" . ($_POST['location_number']? "{$_POST['location_number']}" : "NULL") .
	", street=" . ($_POST['location_street']? "'{$_POST['location_street']}'" : "NULL") .
	", complement=" . ($_POST['location_complement']? "'{$_POST['location_complement']}'" : "NULL") .
	", city=" . ($_POST['location_city']? "'{$_POST['location_city']}'" : "NULL") .
	", state=" . ($_POST['location_state']? "'{$_POST['location_state']}'" : "NULL") .
	", zipcode=" . ($_POST['location_zipcode']? "'{$_POST['location_zipcode']}'" : "NULL") .
	", phone=" . ($_POST['location_phone']? "'{$_POST['location_phone']}'" : "NULL") .
	", cellphone=" . ($_POST['location_cellphone']? "'{$_POST['location_cellphone']}'" : "NULL") .
	", email=" . ($_POST['location_email']? "'{$_POST['location_email']}'" : "NULL") .
	" WHERE id ='{$contacts['locationcontact']}' LIMIT 1");

	// Atualiza contatos
	query_bd("UPDATE contacts SET " .
	"name=" . ($_POST['manager_name']? "\"{$_POST['manager_name']}\"" : "NULL") .
	", number=" . ($_POST['manager_number']? "{$_POST['manager_number']}" : "NULL") .
	", street=" . ($_POST['manager_street']? "'{$_POST['manager_street']}'" : "NULL") .
	", complement=" . ($_POST['manager_complement']? "'{$_POST['manager_complement']}'" : "NULL") .
	", city=" . ($_POST['manager_city']? "'{$_POST['manager_city']}'" : "NULL") .
	", state=" . ($_POST['manager_state']? "'{$_POST['manager_state']}'" : "NULL") .
	", zipcode=" . ($_POST['manager_zipcode']? "'{$_POST['manager_zipcode']}'" : "NULL") .
	", phone=" . ($_POST['manager_phone']? "'{$_POST['manager_phone']}'" : "NULL") .
	", cellphone=" . ($_POST['manager_cellphone']? "'{$_POST['manager_cellphone']}'" : "NULL") .
	", email=" . ($_POST['manager_email']? "'{$_POST['manager_email']}'" : "NULL") .
	" WHERE id ='{$contacts['managercontact']}' LIMIT 1");

	header( "Location: location.php?id={$_POST['id']}&msg=" . urlencode("Location data update succesfully.") );
	die();
}

// Busca todos os dados da locacao
$location = query_fetch("SELECT * FROM locations WHERE id='{$_GET['id']}'");

// Se nao existe, cai fora
if (!$location)
{
    response_404();
}

// Busca contatos
$location_contact = query_fetch("SELECT * FROM contacts WHERE id={$location['locationcontact']} LIMIT 1");
$manager_contact = query_fetch("SELECT * FROM contacts WHERE id={$location['managercontact']} LIMIT 1");

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Edit Location');
adicionar_js('input-format.js');
adicionar_js('add-remove.js');
pagina_head();

/* pega todos tickets ranges */
$ticket_range_result = query_bd("SELECT ticket_start, ticket_end FROM ticket_ranges WHERE location_id={$location['id']}");
$n_ticket_ranges = mysql_affected_rows();

?>
<script type='text/javascript' language="JavaScript">

function addTicketRange() {
    var html = '<span ticket_range_' + ticket_range + '>' +

	'<label for=ticket_start_' + ticket_range + '>Start ticket:</label> ' +
	'$<input type=text id=ticket_start_' + ticket_range + ' name="ticket_starts[]" value="" ' +
	'title="Please enter a value greater than zero" onChange="format_int(this)" size=6 maxlength=6> ' +

	'<label for=ticket_end_' + ticket_range + '>End ticket:</label> ' +
	'<input type=text id=ticket_end_' + ticket_range + ' name="ticket_ends[]" value="" ' +
	'title="Please enter a value greater than zero" onChange="format_int(this)" size=6 maxlength=6> ' +

	'<a href="" title="Remove this ticket range entry" onclick="javascript:removeElement(\'ticket_range_' + ticket_range + '\'); return false;">' +
    '<small>Remove</small></a><br>' +
    '</span>'

	addElement('ticket_ranges', 'span', 'ticket_range_' + ticket_range, html);
	ticket_range++;
};

var ticket_range = <?php echo $n_ticket_ranges ?>;

</script>
<?php

// Mostra opcao de cancelar edicao
echo "<ul id=opcoes>";
echo "<li class='negative'><a href='location.php?id={$location['id']}'><img src='img/cancel.png' alt=''>Cancel Edit</a></li>";
echo "</ul><br>";

echo "<form id=new_location class=big_form method=POST action='location_edit.php'>";
echo "<h1>Edit Location's data</h1><br>";
echo "<input type=HIDDEN name=id value={$location['id']}>";
echo "<label for=location_name>Location name:</label> <input type=TEXT id=location_name name=location_name value=\"{$location_contact['name']}\" size=40 maxlength=80><br>";
echo "<label for=workingtime>Working time:</label> <input type=TEXT id=workingtime name=workingtime value='{$location['workingtime']}' size=40 maxlength=80><br>";

echo "<h2><h2>Tickets range</h2><br>";

/* busca por tickets ranges e mostra form */
echo "<div id=ticket_ranges>";
$n = 0;
while ($ticket_range = mysql_fetch_array($ticket_range_result))
{
    echo "<span id=ticket_range_{$n}>";

	echo "<label for=ticket_start_{$n}>Start ticket:</label> ";
	echo "$<input type=text id=ticket_start_{$n} name='ticket_starts[]' value='{$ticket_range['ticket_start']}' ";
	echo "title='Please enter a value greater than zero' onChange='format_int(this)' size=6 maxlength=6> ";

	echo "<label for=ticket_end_{$n}>End ticket:</label> ";
	echo "<input type=text id=ticket_end_{$n} name='ticket_ends[]' value='{$ticket_range['ticket_end']}' ";
	echo "title='Please enter a value greater than zero' onChange='format_int(this)' size=6 maxlength=6> ";

	echo "<a href='javascript:void(0);' title='Remove this ticket range entry' onclick='javascript:removeElement(\"ticket_range_{$n}\"); return false;'><small>Remove</small></a><br>";
    echo "</span>";
    $n++;
}
unset($ticket_range_result);
echo "</div>";
echo "<br><input type='button'  value='Add Ticket Range' onclick='addTicketRange();'>";

echo "<hr><h2>Location Contact</h2><br>";
echo "<label for=location_number>Number:</label> <input type=TEXT id=location_number name=location_number value='{$location_contact['number']}' size=8 onChange='format_int(this)'>";
echo " <label for=location_street>Street:</label> <input type=TEXT id=location_street name=location_street value='{$location_contact['street']}' size=30 maxlength=50>";
echo " <label for=location_complement>Complement:</label> <input type=TEXT id=location_complement name=location_complement value='{$location_contact['complement']}' size=10 maxlength=30><br>";
echo "<label for=location_city>City:</label> <input type=TEXT id=location_city name=location_city value='{$location_contact['city']}' size=10 maxlength=30>";
echo " <label for=location_state>State:</label> <input type=TEXT id=location_state name=location_state value='{$location_contact['state']}' size=8 maxlength=10>";
echo " <label for=location_zipcode>Zipcode:</label> <input type=TEXT id=location_zipcode name=location_zipcode value='{$location_contact['zipcode']}' size=6 maxlength=10><br>";
echo "<label for=location_phone>Phone:</label> <input type=TEXT id=location_phone name=location_phone value='{$location_contact['phone']}' size=12 maxlength=20>";
echo " <label for=location_cellphone>Cellphone:</label> <input type=TEXT id=location_cellphone name=location_cellphone value='{$location_contact['cellphone']}' size=12 maxlength=20><br>";
echo "<label for=location_email>Email:</label> <input type=TEXT id=location_email name=location_email value='{$location_contact['email']}' size=20 maxlength=30>";

echo "<hr><h2>Manager Contact</h2><br>";
echo "<label for=manager_name>Manager name:</label> <input type=TEXT id=manager_name name=manager_name value=\"{$manager_contact['name']}\" size=40 maxlength=80><br>";
echo "<label for=manager_number>Number:</label> <input type=TEXT id=manager_number name=manager_number value='{$manager_contact['number']}' size=8 onChange='format_int(this)'>";
echo " <label for=manager_street>Street:</label> <input type=TEXT id=manager_street name=manager_street value='{$manager_contact['street']}' size=30 maxlength=50>";
echo " <label for=manager_complement>Complement:</label> <input type=TEXT id=manager_complement name=manager_complement value='{$manager_contact['complement']}' size=10 maxlength=30><br>";
echo "<label for=manager_city>City:</label> <input type=TEXT id=manager_city name=manager_city value='{$manager_contact['city']}' size=10 maxlength=30>";
echo " <label for=manager_state>State:</label> <input type=TEXT id=manager_state name=manager_state value='{$manager_contact['state']}' size=8 maxlength=10>";
echo " <label for=manager_zipcode>Zipcode:</label> <input type=TEXT id=manager_zipcode name=manager_zipcode value='{$manager_contact['zipcode']}' size=6 maxlength=10><br>";
echo "<label for=manager_phone>Phone:</label> <input type=TEXT id=manager_phone name=manager_phone value='{$manager_contact['phone']}' size=12 maxlength=20>";
echo " <label for=manager_cellphone>Cellphone:</label> <input type=TEXT id=manager_cellphone name=manager_cellphone value='{$manager_contact['cellphone']}' size=12 maxlength=20><br>";
echo "<label for=manager_email>Email:</label> <input type=TEXT id=manager_email name=manager_email value='{$manager_contact['email']}' size=20 maxlength=30>";

echo "<hr><h2>Location Information</h2><br>";
echo "<label for=manager_payrate>Manager payrate:</label> <input type=text id=manager_payrate name=manager_payrate value='{$location['manager_payrate']}' size=5 onChange='format_money(this)'><br>";
echo "<label for=valet_payrate>Valet payrate:</label> <input type=text id=valet_payrate name=valet_payrate value='{$location['valet_payrate']}' size=5 onChange='format_money(this)'><br>";
echo "<label for=insurance_tax>Insurance tax per car:</label> <input type=text id=insurance_tax name=insurance_tax size=5 value='{$location['insurance_tax']}' onChange='format_money(this)'><br>";
echo "<label for=tip_percent>Tip percent income:</label> <input type=text id=tip_percent name=tip_percent size=5 value='" . ($location['tip_percent']*100.0) . "' onChange='format_int(this)'>%<br>";

echo "<label for=obs>Observations:</label><br><textarea id=obs name=obs cols=40 rows=5>";
echo $location['obs'];
echo "</textarea>";
echo "<hr>";
echo "<input type=SUBMIT name=submit value='Submit'>";

echo "</form>";

// Finaliza pagina
pagina_fim();
?>
